var selectCouponId;
var selectTypeId;
var selectMoney;
var dayCount
$(function(){
    var bd_vid = getUrlParam('bd_vid');
    if(bd_vid && bd_vid != ''){
        localStorage.setItem('bd_vid',bd_vid);
    }
    var keyword = getUrlParam('keyword');
    if(keyword && keyword != ''){
        localStorage.setItem('keyword',keyword);
    }
    var a_user= getUrlParam('a_user');
    if(a_user && a_user != ''){
        localStorage.setItem('a_user',a_user);
    }
    var a_planid =  getUrlParam('a_planid');
    if(a_planid && a_planid != ''){
        localStorage.setItem('a_planid',a_planid);
    }
    var a_unitid = getUrlParam('a_unitid');
    if(a_unitid && a_unitid != ''){
        localStorage.setItem('a_unitid',a_unitid);
    }
    var a_keywordid = getUrlParam('a_keywordid');
    if(a_keywordid && a_keywordid != ''){
        localStorage.setItem('a_keywordid',a_keywordid);
    }
});


//获取url中的参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if ( r != null ){
        return decodeURI(r[2]);
    }else{
        return '';
    }
}
function searchOpen() {
    let text = $('#searchText').val()
    if (text) {
        window.location.href = '/search?keyword=' + text
    }
}

function hideBuyModelEvent(){
    let token = localStorage.getItem(TOKEN)
    if(token){
        if ($("#singleBuyModal").length > 0) {
            let one_pay = $("#onePay").val();
            if(one_pay > 0){
                showSingle();
            }
        } else {
            sendCoupon();
        }
    }
}


/**
 * 根据订单获取文件路径
 * @param orderNo
 */
function getFilePath(orderNo){
    $.ajax({
        url: '/api/order/getPath',
        method: 'GET',
        data:{
            order:orderNo,
        },
        success: function(res) {
            if(res.data.path){
                if(!res.data.title){
                    res.data.title = '未命名文档';
                }
                let fileExtension = res.data.path.split('.').pop();
                let name =  res.data.title+'.'+fileExtension;
                getFile(res.data.path,name);
            }else{
                layer.msg("文件下载失败");
            }
        },
        error: function() {
            layer.msg("文件下载失败");
        }
    });

}


$(function(){
    $('#buyModal')[0].addEventListener('hide.bs.modal', hideBuyModelEvent);
    headerKeyword();
    $("#searchText").focus(function(){
        $("#header_keyword").show();
    });
    $("#searchText").hover(function(){
        $("#header_keyword").show();
    });
    $("#searchText").blur(function(){
        $("#header_keyword").mouseleave(function(){
            $("#header_keyword").hide();
        });
    });
    $("#header_keyword").mouseleave(function(){
        $("#header_keyword").hide();
    });
    $(".wx-pay").click(function(){
        let contract_id = $('#contract_id').text();
        let token = localStorage.getItem(TOKEN)
        var info = localStorage.getItem(INFO);
        if(info){
            info = JSON.parse(info);
            var bd_vid =info.bd_vid;
            var keyword = info.keyword;
            var a_user = info.userid;
            var a_planid = info.planid;
            var a_unitid =info.unitid;
            var a_keywordid = info.keywordid;
        }else{
            var bd_vid = localStorage.getItem('bd_vid');
            var keyword =localStorage.getItem('keyword');
            var a_user =localStorage.getItem('a_user');
            var a_planid=localStorage.getItem('a_planid');
            var a_unitid =localStorage.getItem('a_unitid');
            var a_keywordid = localStorage.getItem('a_keywordid');
        }
        $.ajax({
            url: "/api/order/pay",
            type: "POST",
            data:{
                payid:selectTypeId,
                contract_id:contract_id,
                return_url:'/',
                coupon_id:selectCouponId,
                type:'wechat',
                bd_vid:bd_vid,
                keyword: keyword,
                userid: a_user,
                planid:a_planid,
                unitid:a_unitid,
                keywordid:a_keywordid,
                type_mode:'pcPay'
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + token);
            },
            success: function (res) {
               if(res.data.code == 200){
                   location.href='/pay?order_no='+res.data.order_no;
               }
            }
        });
    });

    $(".ali-pay").click(function(){
        let contract_id = $('#contract_id').text();
        let token = localStorage.getItem(TOKEN)
        var info = localStorage.getItem(INFO);
        if(info){
            info = JSON.parse(info);
            var bd_vid =info.bd_vid;
            var keyword = info.keyword;
            var a_user = info.userid;
            var a_planid = info.planid;
            var a_unitid =info.unitid;
            var a_keywordid = info.keywordid;
        }else{
            var bd_vid = localStorage.getItem('bd_vid');
            var keyword =localStorage.getItem('keyword');
            var a_user =localStorage.getItem('a_user');
            var a_planid=localStorage.getItem('a_planid');
            var a_unitid =localStorage.getItem('a_unitid');
            var a_keywordid = localStorage.getItem('a_keywordid');
        }
        $.ajax({
            url: "/api/order/pay",
            type: "POST",
            data:{
                payid:selectTypeId,
                contract_id:contract_id,
                coupon_id:selectCouponId,
                type:'alipay',
                type_mode:'pcPay',
                host:'',
                bd_vid:bd_vid,
                keyword: keyword,
                userid: a_user,
                planid:a_planid,
                unitid:a_unitid,
                keywordid:a_keywordid,
                return_url:location.href
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Authorization", "Bearer " + token);
            },
            success: function (res) {
                if(res.data.code == 200){
                    const div=document.createElement('divform');
                    div.innerHTML=res.data.data;
                    document.body.appendChild(div);
                    document.forms['alipay_submit'].acceptCharset='GBK';
                    document.forms['alipay_submit'].submit();
                }else{
                    layer.msg("唤起支付失败 请稍后重试");
                }
            }
        });
    });
});
// 切换VIP
function selectVip(div,price,describe,id) {
    selectTypeId = id;
    selectMoney = price;
    $('.buy-item').removeClass('active')
    $(div).addClass('active')
    $(".buy-bottom p").eq(0).text(describe);
    var money =  formatCurrency(price/100);
    $("#final_money").text(money);
    getCoupon();
    $('#coupon_dropdown_btn').text("点击使用优惠券");
}
function show(){
    payType();
}
function payType(){
   let info =  localStorage.getItem(INFO);
    if(info){
        info = JSON.parse(info);
        if(info.final == 1){
            layer.msg('您已是永久会员无需再次开通');
            return '';
        }
    }
    $('#buyModal').modal('show');
    $.ajax({
        url: "/api/orderType/list",
        type: "GET",
        data:{type:1},
        success: function (res) {
            var htmlStr = '';
            if(res.code ==  200){
                for(var i in res.data){
                    var money = formatCurrency(res.data[i].show_price/100);
                    htmlStr+=` <div class="buy-item" onclick="selectVip(this,${res.data[i].price},'${res.data[i].describe}',${res.data[i].id})">
                        <p class="name">${res.data[i].tag}</p>
                        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor"
                             class="bi bi-check-lg buy-icon" viewBox="0 0 16 16">
                            <path d="M12.736 3.97a.733.733 0 0 1 1.047 0c.286.289.29.756.01 1.05L7.88 12.01a.733.733 0 0 1-1.065.02L3.217 8.384a.757.757 0 0 1 0-1.06.733.733 0 0 1 1.047 0l3.052 3.093 5.4-6.425a.247.247 0 0 1 .02-.022Z"/>
                        </svg>
                        <div class="price">
                            <strong>￥<i>${money}</i></strong>
                                <em class="label">/${res.data[i].label}</em>
                        </div>
                    </div>`;
                }
                $(".buy-container").html(htmlStr);
                $(".buy-item").eq(0).click();
            }
        }
    });
}

function sendCoupon(){
    let token = localStorage.getItem(TOKEN)
    $.ajax({
        url: "/api/order/sendCoupon",
        type: "GET",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        },
        success: function (res) {
           if(res.code == 200){
               $("#couponModal").modal('show');
                getCouponImg();
           }
        }
    });
}

function getCouponImg(){
    $.ajax({
        url: "/api/order/couponImg",
        type: "GET",
        success: function (res) {
            if(res.code == 200){
                $("#couponImg").attr("src",res.data.image);
            }
        }
    });
}


function setCoupon(div,price,couponId) {
    selectCouponId = couponId;
    var money =  formatCurrency((selectMoney-price)/100);
    $("#final_money").text(money);
    $('#coupon_dropdown_btn').text($(div).text())
}

function showBuyAgain(){
    $("#couponModal").modal('hide');
    payType();
}


function getFile(fileUrl,name){
    $.ajax({
        url: fileUrl,
        method: 'GET',
        xhrFields: {
            responseType: 'blob' // 必须指定返回的数据类型为 blob
        },
        success: function(data) {
            // 创建一个隐藏的链接元素
            var downloadLink = document.createElement('a');
            downloadLink.href = window.URL.createObjectURL(data);
            downloadLink.download = name; // 设置下载的文件名
            document.body.appendChild(downloadLink);
            downloadLink.click(); // 触发链接的点击事件进行下载
            document.body.removeChild(downloadLink); // 下载完成后删除链接元素
        },
        error: function() {
            layer.msg("文件下载失败");
        }
    });
}


function getCoupon(){
    let token = localStorage.getItem(TOKEN);
    $.ajax({
        url: "/api/order/getCoupon",
        type: "GET",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        },
        success: function (res) {
            var htmlStr = '<li><a class="dropdown-item" href="#" onclick="setCoupon(this,0,0)">不使用优惠券</a></li>'
            if(res.code == 200){
                var now = $.now()/1000;
                for(var i in res.data){
                    if(now > res.data[i].end){
                        htmlStr+=`<li><a class="dropdown-item" href="#" style="color:#CCCCCC">${res.data[i].title}(已过期)</a></li>`;
                    }else{
                        if(res.data[i].fill_price <= selectMoney){
                            htmlStr+=`<li><a class="dropdown-item" href="#" onclick="setCoupon(this,${res.data[i].price},${res.data[i].id})">${res.data[i].title}</a></li>`;
                        }else{
                            htmlStr+=`<li><a class="dropdown-item" href="#" style="color:#CCCCCC">${res.data[i].title}(未达满减)</a></li>`;
                        }
                    }
                }
                $("#dropdown-menu").html(htmlStr);
            }
        }
    });
}


function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
            num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + num + '.' + cents);
}


function headerKeyword(){
    $.ajax({
        url: "/api/index/keywordList",
        method: "GET",
        data: {limit: 8},
        dataType: "json",
        success: function (data) {
            $("#headerKey").remove();
            let htmlStr = `<div class="hot" id="headerKey"><ul>`;
            var indexStr = '';
            if (data.data.length > 0) {
                for (var i in data.data) {
                    var j = parseInt(i)+1;
                    indexStr += `<li><a class="btn-click active" target="_blank" href="/category?cid=${data.data[i].id}"><span>${data.data[i].title}</span></a></li>`;
                    htmlStr += `<li><i>${j}</i><a href="/search?keyword=${data.data[i].title}" target="_blank"> ${data.data[i].title}</a></li>`
                }
                htmlStr += `</ul></div>`;
            }
            htmlStr += `</ul></div>`;
            $("#header_keyword").html(htmlStr);
            $(".nav-tabs").html(indexStr);
        },
        error: function (error) {

        }
    });
}

/**
 * 获取每天下载量
 */
function getDayNum(){
    let token = localStorage.getItem(TOKEN);
    $.ajax({
        url: "/api/member/downNum",
        type: "GET",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        },
        success: function (res) {
            if(!res.data.count){
                res.data.count = 0;
            }
            dayCount = res.data.count;
            $("#not_vip p").eq(1).text("剩余"+ res.data.count+"下载特权");
            $("#haveDownNum").text(res.data.count);
        }
    });
}
